package com.tea.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.tea.entity.Product;
import com.tea.service.ProductService;
import com.tea.service.impl.ProductServiceImpl;

@WebServlet("/products")
public class ProductServlet extends HttpServlet {
    private final ProductService productService = new ProductServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Product> products = new ArrayList<>();
        String categoryIdParam = req.getParameter("categoryId");
        Long categoryId = null;
        
        // 解析分类ID参数
        if (categoryIdParam != null && !categoryIdParam.isEmpty()) {
            try {
                categoryId = Long.parseLong(categoryIdParam);
                System.out.println("开始查询商品数据，类别ID：" + categoryId);
            } catch (NumberFormatException e) {
                System.err.println("无效的分类ID格式: " + categoryIdParam);
                resp.setStatus(400);
                resp.getWriter().write("{\"error\":\"无效的分类ID格式\"}");
                return;
            }
        }
        
        try {
            // 根据分类ID查询商品
            if (categoryId != null && categoryId > 0) {
                products = productService.getProductsByCategory(categoryId);
            } else {
                products = productService.getAllProducts();
            }
            
            System.out.println("查询到" + products.size() + "条商品数据");
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 返回JSON数据
        resp.setContentType("application/json;charset=UTF-8");
        try {
            com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
            objectMapper.writeValue(resp.getWriter(), products);
        } catch (Exception e) {
            e.printStackTrace();
            resp.setStatus(500);
            resp.getWriter().write("{\"error\":\"生成JSON失败\"}");
        }
    }
}